package com.wzt.lianfirecontrol.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.home.jiankong.JianKongDeviceModel;
import com.wzt.lianfirecontrol.bean.recode.home.system.jiance.SystemBuildModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.WebViewSettingUtils;
import com.wzt.lianfirecontrol.view.GetTopWebView;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONObject;

/**
 * 监测系统
 */
public class WebCadActivity extends BaseActivity implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    private Bundle bundle;

    private View include_head_title;
    private TextView tv_title;
    private ImageView iv_back;
    private ImageView iv_change_cad;

    private SuperSwipeRefreshLayout swipeLayout;
    private WebView webview;
    private WebChromeClient webChromeClient;

    private View include_progress_bar;

    private String url;

    private SystemBuildModel systemBuildModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bundle = getIntent().getExtras();
        if (null != bundle) {
            systemBuildModel = (SystemBuildModel) bundle.getSerializable("data");
        }
        if (null == systemBuildModel){
            finish();
        }
        url = "file:///android_asset/cad/index1.html";
        //url = "http://134.175.220.20/leaflet/index.html";
        setContentView(R.layout.a_web);
        setImmerseLayout(findViewById(R.id.include_head_title), findViewById(R.id.rl_head_content));
        initView();
    }
    private void initView() {
        initHeadView();

        swipeLayout = findViewById(R.id.swipe_container);
        swipeLayout.setOnSwipeRefreshListener(this);
        webview = (GetTopWebView) findViewById(R.id.gtwv_web);
        if (url.contains("needRefresh=0")) {
            swipeLayout.setEnabled(false);
            ((GetTopWebView) webview).setNeedRefresh(false);
        } else {
            InitView.instance().initSuperSwipeLayout(swipeLayout);
        }
        webview.setVerticalScrollbarOverlay(false);
        ((GetTopWebView) webview).setSwipeRefreshLayout(swipeLayout);
        webview.setOverScrollMode(View.OVER_SCROLL_ALWAYS);

        initWebView();

        if (!StringUtils.isEmpty(url)) {
            webview.loadUrl(url);
        }

        include_progress_bar = findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(this, include_progress_bar);

    }

    private void initHeadView() {
        include_head_title = findViewById(R.id.include_head_title);

        include_head_title.setBackgroundColor(getResources().getColor(R.color.main_color));
        tv_title = findViewById(R.id.tv_title);
        tv_title.setTextColor(getResources().getColor(R.color.white));
        tv_title.setText(bundle.getString(ConstData.ACTIONTITLE));

        iv_back = findViewById(R.id.iv_back);
        iv_back.setImageResource(R.drawable.back_white);
        iv_back.setVisibility(View.VISIBLE);

        iv_change_cad = findViewById(R.id.iv_change_cad);
        iv_change_cad.setVisibility(View.VISIBLE);
        iv_change_cad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 切换cad图到带头部选择的设备列表
                Bundle skipToBundle = new Bundle();
                skipToBundle.putSerializable("data", systemBuildModel);
                BannerModel bannerModel = new BannerModel();
                bannerModel.setActionType(ConstData.SHOWFRAG);
                bannerModel.setActionValue(ConstData.BARSELECT);
                bannerModel.setActionTitle(systemBuildModel.getBuildingName());
                setClickAction(bannerModel, skipToBundle);
            }
        });

    }

    /**
     * 初始化webview
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webview = WebViewSettingUtils.getSettingInstance(webview, this);
        webChromeClient = new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                swipeLayout.setRefreshing(false);
                //tv_title.setText(title);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsAlert(view, url, message, result);
            }
        };
        webview.setWebChromeClient(webChromeClient);
        WebViewClient webViewClient = new BridgeWebViewClient((BridgeWebView) webview) {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.e("startUrl", url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.e("shouldOverrideUrl", url);
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e("finishUrl", url);
                webview.loadUrl("JavaScript:bridgeData1(\"" + systemBuildModel.getBuildingId() + "\",\"" +  systemBuildModel.getEquSysId()
                        + "\",\"" + Url.URL_CONTENT+ "\",\"" + Url.POST + "\",\""
                        +  UserInfoModel.getUserToken(WebCadActivity.this) + "\",\"" + UserInfoModel.getCompandId(WebCadActivity.this) + "\")");
            }
        };
        webview.setWebViewClient(webViewClient);

        setJsBridge();
    }

    private void setJsBridge() {
        if (webview instanceof GetTopWebView) {

            //注册showToast方法
            ((GetTopWebView) webview).registerHandler("showToast", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    if (StringUtils.isEmpty(data)) {
                        function.onCallBack("数据不能为空");
                        return;
                    }
                    ToastUtils.showToast(WebCadActivity.this, data);
                    function.onCallBack("toast成功");
                }
            });

            //返回
            ((GetTopWebView) webview).registerHandler("doBack", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (null != webview && webview.canGoBack()) {
                            webview.goBack();
                        }
                        function.onCallBack(" 返回成功");
                    } catch (Exception e) {
                        function.onCallBack(" 返回失败");
                    }
                }
            });

            //注册关闭网页方法
            ((GetTopWebView) webview).registerHandler("closeWeb", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        WebCadActivity.this.finish();
                    } catch (Exception e) {
                        function.onCallBack(" 返回失败");
                    }
                }
            });

            //注册修改preference值方法
            ((GetTopWebView) webview).registerHandler("changePreference", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (!StringUtils.isEmpty(data)) {
                            String[] keyValue = data.split(",");
                            PreferencesUtils.putString(WebCadActivity.this, keyValue[0], keyValue[1]);
                            function.onCallBack(" 修改成功");
                        } else {
                            function.onCallBack(" data不能为空");
                        }
                    } catch (Exception e) {
                        function.onCallBack(" 修改失败");
                    }
                }
            });

            //注册退出登录方法
            ((GetTopWebView) webview).registerHandler("exitAccount", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        UserInfoModel.clearUserLoginMessage(WebCadActivity.this);
                        ActivityCollecter.finishAllActivitys();
                        Bundle bundle1 = new Bundle();
                        if (!StringUtils.isEmpty(data)) {
                            bundle1.putString("error_msg", data);
                        }
                        openActivity(LoginActivity.class, bundle1, 0);
                        function.onCallBack(" 退出成功");
                    } catch (Exception e) {
                        function.onCallBack(" 退出失败");
                    }
                }
            });

            //注册刷新方法
            ((GetTopWebView) webview).registerHandler("refreshCurrentPage", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        webview.reload();
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });

            //注册开启加载动画方法
            ((GetTopWebView) webview).registerHandler("startLoadAnim", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        include_progress_bar.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });

            //注册关闭加载动画方法
            ((GetTopWebView) webview).registerHandler("stopLoadAnim", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        include_progress_bar.setVisibility(View.GONE);
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });

            //获取token
            ((GetTopWebView) webview).registerHandler("getToken", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    function.onCallBack(UserInfoModel.getUserToken(WebCadActivity.this));
                }
            });

            //跳转到监控设备详情
            ((GetTopWebView) webview).registerHandler("skipToVideoDetail", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (!StringUtils.isEmpty(data)) {
                            JianKongDeviceModel jianKongDeviceModel = JSONUtil.jsonObjectToBean(new JSONObject(data), JianKongDeviceModel.class);
                        //    jianKongDeviceModel.setAccessMode("0");
                            bundle.putSerializable("JianKongDeviceModel", jianKongDeviceModel);
                            setClickAction(ConstData.VIDEO, jianKongDeviceModel.getAccessMode(), "监控设备", null, bundle);

                        } else {
                            function.onCallBack(" data不能为空");
                        }
                    } catch (Exception e) {
                        function.onCallBack(" 修改失败");
                    }
                }
            });

            //跳转到设备详情
            ((GetTopWebView) webview).registerHandler("skipToDeviceDetail", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (!StringUtils.isEmpty(data)) {
                            String[] deviceData = data.split(",");
                            Bundle skipToBundle = new Bundle();
                            skipToBundle.putString("equId", deviceData[0]);
                            BannerModel bannerModel = new BannerModel();
                            bannerModel.setActionType(ConstData.SHOWFRAG);
                            bannerModel.setActionValue(ConstData.BAOJINGDETAIL);
                            bannerModel.setActionTitle("详情");
                            setClickAction(bannerModel, skipToBundle);

                        } else {
                            function.onCallBack(" data不能为空");
                        }
                    } catch (Exception e) {
                        function.onCallBack(" 修改失败");
                    }
                }
            });
        }
    }

    @Override
    public void onSwipeRefresh() {
        swipeLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(false);
                if (!StringUtils.isEmpty(url)) {
                    webview.loadUrl(url);
                }
            }
        }, 2000);
    }


    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void onBackPressed() {
        if (null != webview) {
            if (webview.canGoBack()) {
                webview.goBack();
                return;
            }
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // webview 内存泄漏优化
        if (webview!=null) {

            webview.setWebViewClient(null);
            webview.setWebChromeClient(null);
            webview.loadDataWithBaseURL(null,"","text/html","utf-8",null);
            webview.clearHistory();
            ((ViewGroup)webview.getParent()).removeView(webview);
            webview.destroy();
            webview = null;

        }
    }

}
